package main.monitor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Stack;

public class URLPool {

	private static URLPool Instance;
	private Stack<String> stack;
	
	private URLPool(){
		stack = new Stack<String>();
	}
	
	public static URLPool getInstance(){
		if(Instance == null){
			Instance = new URLPool();
		}
		return Instance;
	}
	
	public void batchPush(List<String> URLS){
		for(String URL : URLS){
			if(!stack.contains(URL)){
				stack.push(URL);
			}
		}
	}
	
	public void pushURL(String URL){
		if(!stack.contains(URL)){
			stack.push(URL);
		}
	}
	
	public boolean hasNext(){
		return !(stack.isEmpty());
	}
	
	public String popURL(){
		if(hasNext()){
			return stack.pop();
		} else {
			return null;
		}
	}
	
	public String fakeHeader(String url){
//        String url = "https://nj.lianjia.com/ershoufang/103100569075.html";
        HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon;)");
        conn.setRequestProperty("referer", "http://www.baidu.com");
        
        InputStream is = null;
		try {
			is = conn.getInputStream();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String strLine = "";
        try {
			while ((strLine = br.readLine()) != null) {
			    sb.append(strLine.trim());
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//        System.out.println(sb.toString());
		
		return sb.toString();
	}
}
